package cn.whao.guli.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpCookie;
import org.springframework.http.ResponseCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.UUID;

/**
 * ClassName: MyTokenGatewayFilterFactory
 * Package: cn.whao.guli.gateway.filter
 * Description: 过滤请求，请求头中如果请求头中没有token则添加token
 *
 * @Author 王豪
 * @Create 2024/11/28 20:10
 * @Version 1.0
 */
@Component
public class MyTokenGatewayFilterFactory extends AbstractGatewayFilterFactory {
    @Override
    public GatewayFilter apply(Object config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                ServerHttpRequest request = exchange.getRequest();
                MultiValueMap<String, HttpCookie> cookies = request.getCookies();
                HttpCookie httpCookie = cookies.getFirst("token");
                if (httpCookie == null) {
                    ServerHttpResponse response = exchange.getResponse();
                    MultiValueMap<String, ResponseCookie> c = response.getCookies();
                    c.add("token", ResponseCookie.from("token", UUID.randomUUID().toString()).build());
                }
                return chain.filter(exchange);
            }
        };
    }
}
